<template>
  <div class="doctor-add">
    <h2>新增医生信息</h2>
    <el-form :model="form" ref="formRef" label-width="100px" :rules="rules">
      <el-form-item label="医生姓名" prop="doctorName">
        <el-input v-model="form.doctorName" placeholder="请输入内容" />
      </el-form-item>
      <el-form-item label="上传照片" prop="photo">
        <el-upload
          class="avatar-uploader-circle"
          :show-file-list="false"
          :action="'/'"
          :http-request="customUpload"
        >
          <template #default>
            <div class="avatar-wrapper">
              <img v-if="form.photo" :src="form.photo" class="avatar-circle" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div v-if="form.photo" class="avatar-mask" @click.stop="removePhoto">
                <i class="el-icon-delete"></i>
              </div>
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="所属院区" prop="campusId">
        <el-select v-model="form.campusId" placeholder="请选择院区">
          <el-option v-for="item in campusOptions" :key="item.id" :label="item.campusName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属科室" prop="departmentId">
        <el-cascader
          v-model="form.departmentId"
          :options="departmentOptions"
          placeholder="请选择科室"
          :props="{ checkStrictly: false, emitPath: false, value: 'value', label: 'label', children: 'children' }"
          clearable
          filterable
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="医生职称" prop="jobTitleId">
        <el-select v-model="form.jobTitleId" placeholder="请选择医生职称">
          <el-option v-for="item in jobTitleOptions as any[]" :key="item.id" :label="item.jobTitle" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="医生标签" prop="laberIds">
        <el-select v-model="form.laberIds" multiple placeholder="请选择">
          <el-option v-for="item in labelOptions as any[]" :key="item.id" :label="item.label" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="挂号费" prop="copayfee">
        <el-input-number v-model="form.copayfee" :min="0" />
      </el-form-item>
      <el-form-item label="诊查费" prop="consultationfee">
        <el-input-number v-model="form.consultationfee" :min="0" />
      </el-form-item>
      <el-form-item label="医生简介" prop="briefly">
        <el-input v-model="form.briefly" type="textarea" placeholder="请输入内容" />
      </el-form-item>
      <el-form-item label="医生状态" prop="status">
        <el-switch v-model="form.status" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {axioswmedical} from '@/http/axiosWrtie'
import {axiosrmedical} from '@/http/axiosRead'
import {axiosimg} from '@/http/axiosWrtie'
import { useRouter } from 'vue-router'

const router = useRouter()
const formRef = ref()
const form = reactive({
  doctorName: '',
  photo: '',
  campusId: null,
  departmentId: null,
  jobTitleId: null,
  copayfee: 60,
  consultationfee: 0,
  briefly: '',
  laberIds: [],
  status: true
})

// 选项数据
interface CampusOption {
  id: number | string;
  campusName: string;
}

interface JobTitleOption {
  id: number | string;
  jobTitle: string;
}

interface LabelOption {
  id: number | string;
  label: string;
}

interface DepartmentOption {
  id: number | string;
  label: string;
  value: number | string;
  children?: DepartmentOption[];
}

const campusOptions = ref<CampusOption[]>([])
const departmentOptions = ref<DepartmentOption[]>([])
const jobTitleOptions = ref<JobTitleOption[]>([])
const labelOptions = ref<LabelOption[]>([])

// 获取下拉选项数据
const fetchOptions = async () => {
  try {
    // 院区
    const campusRes = await axiosrmedical.get('/Campus/GetCampus')
    if (campusRes.data.code === 200) {
      campusOptions.value = campusRes.data.data.map((item: any) => ({
        id: item.id,
        campusName: item.campusName
      }))
    }
    // 职称
    const jobTitleRes = await axiosrmedical.get('/JobTitle/GetJobTitle')
    if (jobTitleRes.data.code === 200) {
      jobTitleOptions.value = jobTitleRes.data.data.map((item: any) => ({
        id: item.id,
        jobTitle: item.jobTitle
      }))
    }
    // 标签
    const labelRes = await axiosrmedical.get('/Label/GetLabel')
    if (labelRes.data.code === 200) {
      labelOptions.value = labelRes.data.data.map((item: any) => ({
        id: item.id,
        label: item.label
      }))
    }
    // 科室（级联）
    const departmentRes = await axiosrmedical.get('/Department/GetAllDepartments')
    if (departmentRes.data.code === 200) {
      departmentOptions.value = departmentRes.data.data.map((item: any) => ({
        id: item.id,
        label: item.departmentName,
        value: item.id,
        children: (item.children || []).map((child: any) =>
          typeof child === 'object' ? {
            id: child.id,
            label: child.departmentName,
            value: child.id
          } : {
            label: child,
            value: child
          }
        )
      }))
    }
  } catch (e) {
    ElMessage.error('下拉选项获取失败')
  }
}

// 上传图片自定义方法
const customUpload = async (option: any) => {
  const formData = new FormData()
  formData.append('file', option.file)
  try {
    const res = await axiosimg.post('/FileUpload/UploadFile', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    let url = res.data
    if (typeof url === 'object' && url.url) url = url.url
    form.photo = url
    ElMessage.success('上传成功')
    option.onSuccess(res.data)
  } catch (e) {
    ElMessage.error('上传失败')
    option.onError(e)
  }
}
const removePhoto = () => {
  form.photo = ''
}

// 表单校验规则
const rules = {
  doctorName: [{ required: true, message: '请输入医生姓名', trigger: 'blur' }],
  photo: [{ required: true, message: '请上传照片', trigger: 'change' }],
  campusId: [{ required: true, message: '请选择院区', trigger: 'change' }],
  departmentId: [{ required: true, message: '请选择科室', trigger: 'change' }],
  jobTitleId: [{ required: true, message: '请选择医生职称', trigger: 'change' }],
  copayfee: [{ required: true, message: '请输入挂号费', trigger: 'blur' }],
  consultationfee: [{ required: true, message: '请输入诊查费', trigger: 'blur' }],
  briefly: [{ required: true, message: '请输入简介', trigger: 'blur' }]
}

// 提交
const onSubmit = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    try {
      const res = await axioswmedical.post('/Doctor/AddDoctor', form)
      if (res.data.code === 200) {
        ElMessage.success('新增成功')
        router.back()
      } else {
        ElMessage.error(res.data.msg || '新增失败')
      }
    } catch (e) {
      ElMessage.error('网络错误')
    }
  })
}
const onCancel = () => {
  router.back()
}

onMounted(() => {
  fetchOptions()
})
</script>

<style scoped>
.doctor-add {
  padding: 24px;
  background: #fff;
}
.avatar-uploader-circle {
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.avatar-wrapper {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  border: 1px dashed #d9d9d9;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafbfc;
  cursor: pointer;
}
.avatar-circle {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 50%;
  max-width: 100px;
  max-height: 100px;
}
.avatar-uploader-icon {
  font-size: 32px;
  color: #8c939d;
}
.avatar-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.4);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s;
  cursor: pointer;
}
.avatar-wrapper:hover .avatar-mask {
  opacity: 1;
}
</style>